//
//  HMOAuthViewController.swift
//  Weibo
//
//  Created by Apple on 2017/7/12.
//  Copyright © 2017年 KY. All rights reserved.
//

import UIKit
import SVProgressHUD

let AppKey = "1648205846"
let AppSecret = "a4e9f48597273887d24d2cb0c2e3866e"
let Redirect_Uri = "http://www.itcast.cn"

class HMOAuthViewController: UIViewController {

    //  MARK:   --懒加载控件
    private lazy var webView: UIWebView = UIWebView()
    
    //  自定义视图
    override func loadView() {
        view = webView
        //  设置代理
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        setupNavUI()
        loadLoginRequest()
    }
    
    //  加载登录页面
    private func loadLoginRequest() {
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_Uri)"
        print(urlStr)
        let urlRequest = URLRequest(url: URL(string: urlStr)!)
        webView.loadRequest(urlRequest)
    }
    
    //  设置导航栏按钮
    private func setupNavUI() {
        navigationItem.title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
    }
    
    //  MARK:   --导航栏事件处理
    @objc private func cancelAction() {
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func autoFillAction() {
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = 'hao123guohaibin@163.com';document.getElementById('passwd').value = 'guohaibin123';document.getElementById('passwd').focus()")
    }

   
    
    
}

//  MARK:   --UIWebViewDelegate
extension HMOAuthViewController: UIWebViewDelegate {
    
    //  将要加载网络请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let url = request.url else {
            return false
        }
        
        if url.absoluteString.hasPrefix(Redirect_Uri) {
            //  是授权地址
            
            print(url.absoluteString)
            //  获取请求参数
            if let query = url.query, query.hasPrefix("code=") {
                //  有参数，并且以code开头，获取code参数对应的值
                let code = query.substring(from: "code=".endIndex)
                //  获取令牌
                HMUserAccountViewModel.sharedUserAccount.requestAccesstoken(code: code, callBack: { (isSuccess) in
                    if isSuccess {
                        print("登录成功")
                        self.dismiss(animated: false, completion: {
                            //  一定要等到当前控制器dismis完成以后切换控制器，否则会有父视图控制器也就是Main释放不了
                            NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotificationName), object: self)
                        })
                        
                    } else {
                        print("登录失败")
                    }
                })
                
            } else {
                //  取消授权
                dismiss(animated: true, completion: nil)
            }
            
            return false
        } else {
            //  不是授权地址
            return true
        }
        
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
}

